package com.cssw.fyzb.tps.api.adapay;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.tps.config.adapay.AdapayConfig;
import com.cssw.fyzb.tps.service.pay.AliPayService;
import com.cssw.fyzb.tps.util.StringUtil;
import com.huifu.adapay.model.Payment;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yangyiqun
 * @Date: 2021/1/06 22:29
 */
@Function(description = "发起支付", parameters = {
        @Parameter(name = "outTradeNo", type = Type.String, description = "外部单号", required = true),
        @Parameter(name = "goodsTitle", type = Type.String, description = "商品名称", required = true),
        @Parameter(name = "goodsDesc", type = Type.String, description = "商品描述", required = true),
        @Parameter(name = "payAmt", type = Type.String, description = "金额", required = true),
        @Parameter(name = "expend", type = Type.String, description = "支付渠道额外参数，JSON格式，条件可输入，详见 支付渠道 expend参数", required = false)
})
@Component
public class WxAppAdapay implements Action {

    private static final Logger logger = LoggerFactory.getLogger(WxAppAdapay.class);

    @Autowired
    private AdapayConfig adapayConfig;

    @Override
    public Response execute(Request request) throws Exception {
        String outTradeNo = request.getString("outTradeNo");
        String goodsTitle = request.getString("goodsTitle");
        String goodsDesc = request.getString("goodsDesc");
        String payAmt = request.getString("payAmt");
        String expend = request.getString("expend");

        try {
            Map<String, Object> paymentParams = new HashMap<>(10);
            paymentParams.put("app_id", adapayConfig.getAppId());
            paymentParams.put("order_no", outTradeNo);
            paymentParams.put("pay_channel", "wx_lite");
            paymentParams.put("pay_amt", payAmt);

            paymentParams.put("goods_title", goodsTitle);
            paymentParams.put("goods_desc", goodsDesc);

            paymentParams.put("div_members", "");
//            paymentParams.put("pay_mode", "delay");
            paymentParams.put("notify_url", adapayConfig.getNotifyUrl());

            if (StringUtil.isNotBlank(expend)){
                paymentParams.put("expend", JSON.parseObject(expend));
            }

            Map<String, Object> payment = Payment.create(paymentParams);

            return Response.success().put("data", payment);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("支付发起失败");
        }
    }
}
